//
//  MusicSecViewController.m
//  A_program
//
//  Created by 杨利佳 on 15/5/22.
//  Copyright (c) 2015年 BayMax. All rights reserved.
//

#import "MusicSecViewController.h"
#import "SANetWorkingTask.h"
#import "MusicSecTableViewCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MusicThiViewController.h"
#import "MJRefresh.h"
#import "MusicSecButton.h"
#import "NovelModel.h"
#import "NovelDatabase.h"
#import "ConnectModel.h"
#import "LoginNextViewController.h"

@interface MusicSecViewController ()<UITableViewDataSource, UITableViewDelegate, MusicCollectButtonDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic,assign) NSInteger detailsPageCount;

@property (nonatomic, retain) NovelModel *novelModel;

@end

@implementation MusicSecViewController

- (void)dealloc
{
    [_tname release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.tableArray = [NSMutableArray array];
        self.detailsPageCount = 2;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.title = self.tname;
    [self createTable];
    [self connect];
    
}


#pragma mark -
#pragma mark 创建table
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _table.alpha = 0.8;
    self.table.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_table];
    [_table release];
    
    _table.dataSource = self;
    _table.delegate = self;
    
    [self.table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.table addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreDate)];
    self.table.footer.automaticallyRefresh = NO;
    UINib *nib = [UINib nibWithNibName:@"MusicSecTableViewCell" bundle:[NSBundle mainBundle]];
    [_table registerNib:nib forCellReuseIdentifier:@"a"];
    
}

- (void)connect
{
    // 网络请求
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=music&condition=hot&device=android&page=1&per_page=20&status=0&tag_name=%@", self.tname];
    [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
        self.tableArray = [result objectForKey:@"list"];
        [self.table reloadData];
    }];

}


#pragma mark -
#pragma mark 上拉加载
- (void)loadMoreDate
{
    if ([self isConnectionAvailable:2]) {
        // 网络请求
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=music&condition=hot&device=android&page=%ld&per_page=20&status=0&tag_name=%@", self.detailsPageCount, self.tname];
    [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
        NSArray *arr = [result objectForKey:@"list"];
        [self.tableArray addObjectsFromArray:arr];
        [self.table reloadData];
    }];
    self.detailsPageCount += 1;
    [self.table.footer endRefreshing];
        
    }
  
}

// 下拉刷新
- (void)loadNewData:(id)sender
{
    if ([self isConnectionAvailable:1]) {
        [self.table reloadData];
        [self.table.header endRefreshing];
    }
   }

//判断网络使用
-(BOOL) isConnectionAvailable:(NSInteger)count{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"没网");
            if (count == 1) {
                [self.table.header endRefreshing];
            }else{
                [self.table.footer endRefreshing];
            }
            
            [self alertView:@"没有网络连接"];
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"用的WIFI");
                     break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            [self alertView:@"使用3G连接"];
            break;
    }
    
    
    return isExistenceNetwork;
}
// 警告框
- (void)alertView:(NSString *)str
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
    [alert setDelegate:self];
    [alert show];
    [alert release];
    
}

#pragma mark -
#pragma mark tableView的协议实现

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicSecTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
    
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.item];
    [cell.showImage sd_setImageWithURL:[dic objectForKey:@"albumCoverUrl290"] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    cell.title.text = [dic objectForKey:@"title"];
    cell.playCounts.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"playsCounts"]];
    cell.tracksCounts.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"tracksCounts"]];
    
    //按钮的id
    NSDictionary *dict = [_tableArray objectAtIndex:indexPath.row];
    
    cell.colButton.collectId = [dict objectForKey:@"id"];
    cell.collectDelegate = self;
    
    //判断收藏
    //功能
    NSUserDefaults *myLoginName = [NSUserDefaults standardUserDefaults];
    NSMutableArray *array = (NSMutableArray *)[NovelDatabase selectNameAlbumId:[cell.colButton.collectId integerValue] loginName:[myLoginName objectForKey:@"loginName"]];
    if (array.count == 0) {
        [cell.colButton setTitle:@"收藏" forState:UIControlStateNormal];
        
    }else{
        [cell.colButton setTitle:@"已收藏" forState:UIControlStateNormal];
    }

    
    
    return cell;
}

// 收藏按钮
- (void)createCollectAction:(NSString *)collect{
    NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];


                NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                    self.novelModel = [[NovelModel alloc]init];
                    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                    [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                    //读取userDefault的信息
                    self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                    self.novelModel.playKind = @"music";
                    self.novelModel.albumIdMin = [collect integerValue];
                    [NovelDatabase insertWithModel:self.novelModel];
                }];

    
}



// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}


// 跳转到下一个界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicThiViewController *third = [[MusicThiViewController alloc] init];
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    third.ID = [dic objectForKey:@"id"];
    [self.navigationController pushViewController:third animated:YES];
    [third release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
